package com.Redis.Utils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.exceptions.JedisConnectionException;

import java.util.ResourceBundle;

import javax.annotation.PostConstruct;

public class RedisPool3 {
	private static JedisPool jedisPool = null;
	
	@PostConstruct
	private static synchronized JedisPool createJedisPool() {
		ResourceBundle bundle = ResourceBundle.getBundle("redis");
		if (bundle == null) {
			throw new IllegalArgumentException("[redis.properties] is not found");
		}
		if (jedisPool == null) {

			JedisPoolConfig config = new JedisPoolConfig();

			config.setMaxTotal(Integer.valueOf(bundle.getString("redis.pool.maxActive")));
	        config.setMaxIdle(Integer.valueOf(bundle.getString("redis.pool.maxIdle")));
	        config.setMaxWaitMillis(Long.valueOf(bundle.getString("redis.pool.maxWait")));
	        config.setTestOnBorrow(Boolean.valueOf(bundle.getString("redis.pool.testOnBorrow")));
	        config.setTestOnReturn(Boolean.valueOf(bundle.getString("redis.pool.testOnReturn")));
	        try {
	        	jedisPool = new JedisPool(config,bundle.getString("redis.ip"),Integer.valueOf(bundle.getString("redis.port")),100000);
			} catch (Exception e) {
				// TODO: handle exception
			}
			
		}

		return jedisPool;
	}

	/**
     * 获取jedis实例
     * 在获取jedis实例方法前，加上序列化
     */
    public synchronized static Jedis getJedis(){
        if(jedisPool!=null){
        	Jedis jedis = null;
        	try {
        		jedis = jedisPool.getResource();        		
			} catch (JedisConnectionException e) {
				e.printStackTrace();
				jedis = null;
			} 
        	return jedis;        
        }else{
            return null;
        }
    }
    /**
     * 释放jedis实例资源
     */
    public static void returnResource(Jedis jedis){
        if(jedis!=null){
            jedis.close();
        }
    }
    /** 
     * Jedis对象出异常的时候，回收Jedis对象资源 
     * @param jedis 
     */  
    public synchronized static void returnBrokenResource(Jedis  jedis){  
        if(jedis != null){  
            jedisPool.returnBrokenResource(jedis);  
        }  
          
    }  
}
